// ==UserScript==
// @name         waipian
// @namespace    npm/vite-plugin-monkey
// @version      20230708.2130
// @author       liuyonghu
// @description  del ads
// @license      ISC
// @icon         
// @homepageURL  https://gitee.com/liuyonghu/del-ads/raw/master/dist/waipian.user.js
// @downloadURL  https://gitee.com/liuyonghu/del-ads/raw/master/dist/waipian.user.js
// @updateURL    https://gitee.com/liuyonghu/del-ads/raw/master/dist/waipian.user.js
// @match        *://*/*
// @run-at       document-start
// ==/UserScript==

const hosts = ["dyxs", "waipian"];
let stopFlag = false;
const initLogEl = () => {
  const logContaner = document.createElement("div");
  logContaner.style.cssText = `position:fixed;
  display: flex;
  flex-direction:column;
    left:20px;
    bottom:30px;
    height: 50vh;
    overflow:hidden;
    font-size: 12px;
    width: 100px;
    padding:5px;
    color: #5f5e5e;
    background-color: transparent;
    text-align:center;
    `;

  const logEl = document.createElement("div");
  logEl.style.cssText = `
left:20px;
bottom:30px;
height:calc(100% - 180px);
font-size: 12px;
width: 100%;
overflow-x:hidden;
overflow-y:auto;
padding:5px;
color: #5f5e5e;
background-color: transparent;
`;

  const clearAction = document.createElement("button");
  clearAction.innerText = "清除";
  clearAction.type = "button";
  clearAction.style.cssText = `
height:40px;
width: 100%;
color: #5f5e5e;
background-color: transparent;
`;
  clearAction.addEventListener("click", () => {
    logEl.innerText = "";
  });

  const stopAction = document.createElement("button");
  stopAction.innerText = "停止运行";
  stopAction.type = "button";
  stopAction.style.cssText = `
  height:40px;
  width: 100%;
  color: #5f5e5e;
  background-color: transparent;
  `;
  stopAction.addEventListener("click", () => {
    stopFlag = true;
  });

  const startAction = document.createElement("button");
  startAction.innerText = "开始运行";
  startAction.type = "button";
  startAction.style.cssText = `
  height:40px;
  width: 100%;
  color: #5f5e5e;
  background-color: transparent;
  `;
  startAction.addEventListener("click", () => {
    stopFlag = false;
  });

  const hideAction = document.createElement("button");
  hideAction.innerText = "隐藏";
  hideAction.type = "button";
  hideAction.style.cssText = `
  height:40px;
  width: 100%;
  color: #5f5e5e;
  background-color: transparent;
  `;
  hideAction.addEventListener("click", () => {
    if (logEl.style.display === "none") {
      logEl.style.display = "block";
      startAction.style.display = "block";
      stopAction.style.display = "block";
      hideAction.innerText = "隐藏";
    } else {
      logEl.style.display = "none";
      startAction.style.display = "none";
      stopAction.style.display = "none";
      hideAction.innerText = "显示";
    }
  });

  logContaner.append(hideAction, clearAction, stopAction, startAction, logEl);
  return () => {
    return {
      logContaner,
      logEl,
      stopAction,
      startAction,
    };
  };
};

const getLogEl = initLogEl();

const appendLogEl = () => {
  document.body.append(getLogEl().logContaner);
};
const hadeInitLogEl = () => {
  try {
    return document.body.contains(getLogEl().logContaner);
  } catch (error) {
    return false;
  }
};

let logFlag = 0;
const logInfo = (info: string) => {
  if (!hadeInitLogEl()) {
    appendLogEl();
  }
  const logEl = getLogEl().logEl;
  logFlag++;
  logEl.innerText = `${logEl.innerText}\n ${logFlag} - ${info}`;
};

(() => {
  let continueFlag = true;
  logInfo("开始检查环境，，，");
  for (let index = 0; index < hosts.length; index++) {
    const element = hosts[index];
    if (location.href.indexOf(element) >= 0) {
      continueFlag = true;
      logInfo("匹配到 hosts");
      break;
    }
  }
  if (location.href.indexOf("play") >= 0) {
    continueFlag = true;
  }
  if (!continueFlag) {
    logInfo("确认，不可执行。");
    return;
  }
  logInfo("开始设置逻辑， 开开心心每一天 ~");
  try {
    const blackList = ["rm-list"];
    const removeEl = (el) => {
      try {
        if (el && el.parentNode) {
          el.parentNode.removeChild(el);
          logInfo(`移除元素 - ${el}`);
        }
      } catch (error) {
        console.warn(error);
      }
    };
    // del ads img;
    const handleAds = () => {
      logInfo(`开始检查元素文档`);
      blackList.forEach((blackItem) => {
        const nodes = document.querySelectorAll(`.${blackItem}`);
        if (nodes.length > 0) {
          const flag = nodes.length - 1;
          for (let index = flag; index >= 0; index -= 1) {
            const element = nodes[index];
            logInfo(`检测到元素 - ${element}`);
            removeEl(element as HTMLElement);
          }
        }
      });
    };
    // del stop img
    const delStopImg = () => {
      const iframeEls = document.querySelectorAll("iframe");
      logInfo(`开始检查元素子文档`);
      if (iframeEls.length > 0) {
        iframeEls.forEach((iframeEl) => {
          if (iframeEl && iframeEl.contentDocument) {
            const closeEl =
              iframeEl.contentDocument.querySelector("#player_pic");
            if (closeEl) {
              logInfo(`检测到元素 - ${closeEl}`);
              removeEl(closeEl);
            }
          }
        });
      }
    };

    const action = () => {
      if (stopFlag) {
        return;
      }
      delStopImg();
      handleAds();
    };
    let oldTimestamp = null as null | number;
    const handleAction = (timeStamp: number) => {
      // logInfo(" == handleAction == ");
      if (oldTimestamp === null) {
        oldTimestamp = timeStamp;
        action();
      }

      if (timeStamp - oldTimestamp >= 2000) {
        action();
        oldTimestamp = timeStamp;
      }
      window.requestAnimationFrame(handleAction);
    };
    logInfo(`开始执行 检查帧`);
    window.requestAnimationFrame(handleAction);
  } catch (error) {
    logInfo("啊，出错了：");
    logInfo(error);
  }
})();
